package com.wosai.teach.handler;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PBarHandler extends Handler {

	public PBarHandler(Activity activity, ProgressBar pbar, TextView tv) {
		this.activity = activity;
		this.pbar = pbar;
		this.tv = tv;
	}

	private Activity activity;

	private ProgressBar pbar;

	private TextView tv;

	private int fileSize;

	@Override
	public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
		tv.setVisibility(View.VISIBLE);
		pbar.setVisibility(View.VISIBLE);
		if (!Thread.currentThread().isInterrupted()) {
			switch (msg.what) {
			case 0:
				this.fileSize = msg.getData().getInt("fileSize");
				pbar.setMax(this.fileSize);
			case 1:
				int curSize = msg.getData().getInt("curSize");
				pbar.setProgress(curSize);
				int result = curSize * 100 / fileSize;
				tv.setText(result + "%");
				break;
			case 2:
				Toast.makeText(activity, "文件下载完成", Toast.LENGTH_LONG).show();
				tv.setVisibility(View.GONE);
				pbar.setVisibility(View.GONE);
				break;
			case -1:
				String error = msg.getData().getString("error");
				Toast.makeText(activity, error, Toast.LENGTH_LONG).show();
				break;
			}
		}
		super.handleMessage(msg);
	}

	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	public int getFileSize() {
		return fileSize;
	}

	public void setPbar(ProgressBar pbar) {
		this.pbar = pbar;
	}

	public void setTv(TextView tv) {
		this.tv = tv;
	}

	public ProgressBar getPbar() {
		return pbar;
	}

	public TextView getTv() {
		return tv;
	}
}
